package com.example.online_exam_system.logic.impl;


import com.alibaba.druid.support.json.JSONUtils;
import com.example.online_exam_system.commons.Result;
import com.example.online_exam_system.commons.TableResult;
import com.example.online_exam_system.dto.QuestionsDto;
import com.example.online_exam_system.dto.TeacherregDto;
import com.example.online_exam_system.entity.Exam;
import com.example.online_exam_system.entity.TestPage;
import com.example.online_exam_system.logic.IQuestionsInfoService;
import com.example.online_exam_system.logic.ITeacherLogicService;
import com.example.online_exam_system.service.*;
import com.example.online_exam_system.utils.DateUtils;
import com.example.online_exam_system.utils.HAUtils;
import com.example.online_exam_system.utils.KaptchaValid;
import com.example.online_exam_system.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Session;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @Description
 * @Author lianglong
 * @Since 2021/12/1 1:06
 **/
@Service
@Slf4j
@Transactional(rollbackFor = RuntimeException.class)
public class TeacherLogicServiceImpl implements ITeacherLogicService {

	@Autowired
	private HttpServletRequest request;
	@Autowired
	private IQuestionsInfoService questionsInfoService;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private TestQuestionsService testQuestionsService;
	@Autowired
	private SubjectService subjectService;
	@Autowired
	private StuSubService stuSubService;
	@Autowired
	private TestPageService testPageService;
	@Autowired
	private StuExamService stuExamService;

	@Override
	public Result teacherLogincheck(Map<String, Object> inParam){
		HttpSession session = request.getSession();
		//判断验证码是否有效
		if (KaptchaValid.isRelsase(request, MapUtils.getString(inParam, "kapText"))) {
			//验证通过   检查用户名密码是否正确
			inParam.put("password",MD5Utils.getMD5(MapUtils.getString(inParam,"password")));
			List<Map<String, Object>> list = teacherService.queryByuserName(inParam);
			if (list != null && list.size() > 0) {
				String username = MapUtils.getString(inParam, "username");
				session.setAttribute("username", username);
				session.setAttribute("identify","teacher");
				// TODO: 2021/11/27  获取页面展示信息
				return Result.ok().msg("欢迎您," + username + "老师").data(username);
			}
			return Result.err().msg("用户名密码不正确");
		} else {
			return Result.err().msg("验证码错误");
		}
	}

	@Override
	public Result teacherRegCheck(TeacherregDto teacherregDto){
		//密码加密
		teacherregDto.setPassword(MD5Utils.getMD5(teacherregDto.getPassword()));
		Map<String,Object> inParam = new HashMap<>();
		inParam.put("username",teacherregDto.getUsername());
		inParam.put("password",teacherregDto.getPassword());
		List<Map<String, Object>> list = teacherService.queryByuserName(inParam);
		if (list == null || list.size() == 0) {
			//将用户信息添加至数据库
			teacherregDto.setRegtime(LocalDateTime.now());
			int insert = teacherService.insert(teacherregDto);
			if (insert > 0) {
				return Result.ok().msg("注册成功");
			}else{
				return Result.err().msg("注册失败  请联系系统管理员");
			}
		} else {
			return Result.err().msg("该用户存在  不允许再次注册");
		}
	}

	@Override
	public Result insertQuestion(QuestionsDto questionsDto) {
		//补充id信息（从前台获取的是subjectname）
		questionsDto = questionsInfoService.addSubjectName(questionsDto);
		//入库
		int  i =questionsInfoService.insertQuestion(questionsDto);
		//插入成功
		if(i==1){
			return new Result().code(200).success(true).msg("添加成功").data(i);
		}
		//插入失败
		return new Result().code(0).success(false).msg("添加失败").data(i);
	}

	@Override
	public TableResult getQuestionsTable(String username){
		//根据用户姓名查找试题列表，其实username没用
		List<QuestionsDto> questionsTable = questionsInfoService.getQuestionsTable(username);
		//循环试题列表
		for(QuestionsDto questionsDto : questionsTable){
			//取出每个试题的id
			String subjectId = questionsDto.getSubjectid();
			String subjectName =MapUtils.getString(subjectService.getSubjectNameById(subjectId),"subjectname") ;
			//将科目名字存入结果
			questionsDto.setSubjectname(subjectName);
		}
		int size = questionsTable.size();
		String count = size +"";
		return new TableResult().code(0).msg("获取数据成功").count(count).data(questionsTable);
	}

	@Override
	public int updateQuestion(Map<String, Object> inParam) {
		//更新试题获取科目名称
		String subjectname = MapUtils.getString(inParam,"subjectname");
		String subjectid = 	subjectService.getSubjectIdByname(subjectname);
		inParam.put("subjectid",subjectid);
		return testQuestionsService.updateQuestion(inParam);
	}

	@Override
	public int deleteQuestion(Map<String, Object> inParam) {

		return testQuestionsService.deleteQuestion(inParam);
	}

	@Override
	public Map<String, Object> getTeacherInfo(String realname) {
		//根据教师姓名获取
		Map<String, Object> teacherInfo1 = teacherService.getTeacherInfo(realname);
		String teacherid = MapUtils.getString(teacherInfo1,"teacherid");
		List<Map<String,Object>> teacherInfo2 = stuSubService.getTeacherSub(teacherid);
		Map<String,Object> teacherInfo3 = new HashMap<>();
		String subjectname = "";
		if(teacherInfo2 !=null){
			for (Map<String,Object> map: teacherInfo2) {
				String subjectname1 = MapUtils.getString(subjectService.getSubjectNameById(MapUtils.getString(map,"subjectid")),"subjectname");
				if (null!=subjectname1){
					subjectname = subjectname +" "+subjectname1;
				}
			}
		}
		teacherInfo3.put("subjectname",subjectname);
		Map<String, Object> teacherInfo = new HashMap<>();
		teacherInfo.putAll(teacherInfo1);
		teacherInfo.putAll(teacherInfo3);
		return teacherInfo;
	}


	@Override
	public List<Map<String, Object>> getAllSubjects() {
		return subjectService.getAllSubjects();
	}

	@Override
	public List<Map<String, Object>> getTeaSubIds(String realname) {
		//获取教师id
		String teacherId = teacherService.getTeacherId(realname);
		//根据教师id获取所受科目id
		List<Map<String,Object>> teasubids = stuSubService.getTeacherSub(teacherId);
		return teasubids;
	}

	@Override
	public int updateTeacherInfo(Map<String, Object> inParam) {
		inParam.put("password2",MD5Utils.getMD5(MapUtils.getString(inParam,"password2")));
		int i = teacherService.updateTeacherInfo(inParam);
		int teacherId = Integer.parseInt(teacherService.getTeacherId(MapUtils.getString(inParam,"username")));
		Object subjects = MapUtils.getObject(inParam,"subjects");
		List<String> subjectnames = HAUtils.castList(subjects,String.class);
		Map<String,Object> param = new HashMap<>();
		param.put("teacherid",teacherId);
		int j = 0;
		int z = 0;
		for(String subjectname : subjectnames){
			String subjectId = subjectService.getSubjectIdByname(subjectname);
			param.put("subjectid",subjectId);
			//更新流程：我们判断老师所受科目的标志为学生id为0
			j += stuSubService.deleteTeaSub(param);
			z += stuSubService.insertTeaSub(param);
		}
		if(i>=0 && z>0 ){
			return 1;
		}else{
			return 0;
		}
	}

	@Override
	public int pwdVerify(Map<String, Object> inParam) {
		String pwd = MD5Utils.getMD5(MapUtils.getString(inParam,"password"));
		String password = teacherService.getPassword(inParam);
		if(pwd.equals(password)){
			return 1;
		}else{
			return 0;
		}

	}

	@Override
	public List<String> getTeaSubs(String teacherId) {
		//根据教师id获取科目id
		List<Map<String, Object>> teaSubIds = this.getTeaSubIds(teacherId);
		List<Integer> teasubids = new ArrayList<>();
		for(Map<String,Object> map:teaSubIds){
			int sujectid = MapUtils.getInteger(map,"subjectid");
			teasubids.add(sujectid);
		}
		List<String> result = new ArrayList<>();
		for(Integer subId:teasubids){
			Map<String, Object> subjectName = subjectService.getSubjectNameById(subId.toString());
			result.add(MapUtils.getString(subjectName,"subjectname"));
		}
		return result;
	}

	@Override
	public List<String> getTeaSubNames2(String realname) {
		//获取教师所受科目id列表
		List<Map<String, Object>> teaSubIds = this.getTeaSubIds(realname);
		List<String> list = new ArrayList<>();
		for(Map<String,Object> map:teaSubIds){
			list.add(MapUtils.getString(map,"subjectname"));
		}
		return list;
	}

	@Override
	public TableResult getQuestionsByteacherName(String realname) {
		List<QuestionsDto> questionsTable = new ArrayList<>();
		List<Map<String, Object>> teaSubIds = this.getTeaSubIds(realname);
		for (Map<String, Object> teaSubId : teaSubIds) {
			Map<String, Object> map = new HashMap<>();
			map.put("subjectid", teaSubId);
			//根据科目id查找试题列表
			List<QuestionsDto> questionsBySubjectId = testQuestionsService.getQuestionsBySubjectId(teaSubId);
			//循环试题列表
			for (QuestionsDto questionsDto : questionsBySubjectId) {
				//取出每个试题的id
				String subjectId = questionsDto.getSubjectid();
				//通过id获取试题名称
				String subjectName = MapUtils.getString(subjectService.getSubjectNameById(subjectId), "subjectname");
				//将科目名字存入结果
				questionsDto.setSubjectname(subjectName);
				//存入结果集
				questionsTable.add(questionsDto);
			}
		}
		int size = questionsTable.size();
		String count = size + "";
		return new TableResult().code(0).msg("获取数据成功").count(count).data(questionsTable);
	}

	@Override
	public TableResult getquestionbyid(Map<String, Object> inParam) {
		List<String> questionIds = HAUtils.castList(MapUtils.getObject(inParam,"questionids"), String.class);
		HttpSession session = request.getSession();
		TableResult questions = this.getQuestionsByteacherName((String) session.getAttribute("username"));
		List<QuestionsDto>  data = (List<QuestionsDto> )questions.getData();
		List<QuestionsDto> result = new ArrayList<>();
		for(QuestionsDto dto : data){
			if(questionIds.contains(dto.getQuestionid())){
				result.add(dto);
			}
		}
		int size = result.size();
		String count = size +"";
		return new TableResult().code(0).msg("获取数据成功").count(count).data(result);
	}

	@Override
	public Result addExamPage(Map<String, Object> inParam) {
		HttpSession session = request.getSession();
		String time = MapUtils.getString(inParam,"time");
		String startTime= "";
		String endTime = "";
		if (time.contains("true")) {
			String [] parts = time.split("true");
			startTime = parts[0];
			endTime = parts[1];
		} else {
			throw new IllegalArgumentException("当前字符串没有true");
		}
		inParam.put("startTime", DateUtils.dateStrToLocalDateTime(startTime.trim()));
		inParam.put("endTime",DateUtils.dateStrToLocalDateTime(endTime.trim()));
		String questionids2 = (String)MapUtils.getObject(inParam,"questions");
		String[] strs= questionids2.split(",");
		List<String> questionids = Arrays.asList(strs);
		int i = 0;
		Random random = new Random();
		StringBuffer testid= new StringBuffer();
		for (int m=0;m<6;m++)
		{
			testid.append(random.nextInt(10));
		}
		log.debug("试卷ID为："+testid.toString());
		for(String questionid : questionids){
			try{
				TestPage testPage = new TestPage();
				BeanUtils.populate(testPage, inParam);
				testPage.setQuestionid(questionid);
				testPage.setSubjectid(subjectService.getSubjectIdByname(MapUtils.getString(inParam,"subjectname")));
				testPage.setTeacherid(Integer.parseInt(teacherService.getTeacherId((String)session.getAttribute("username"))));
				testPage.setTestid(Integer.parseInt(testid.toString()));
				int j= testPageService.insertTestPage(testPage);
				if(j == 1 ){
					i++;
				}
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		if(i == questionids.size()){
			return new Result().msg("新建试卷成功").success(true).data("成功");
		}else{
			return new Result().msg("新建试卷失败").success(false).data("失败");
		}
	}
	@Override
	public Result addExamPage2(Map<String, Object> inParam) {
		HttpSession session = request.getSession();
		String time = MapUtils.getString(inParam,"time2");
		String startTime= "";
		String endTime = "";
		if (time.contains("true")) {
			String [] parts = time.split("true");
			startTime = parts[0];
			endTime = parts[1];
		} else {
			throw new IllegalArgumentException("当前字符串没有true");
		}
		inParam.put("startTime", DateUtils.dateStrToLocalDateTime(startTime.trim()));
		inParam.put("endTime",DateUtils.dateStrToLocalDateTime(endTime.trim()));
		String questionidNum = (String)MapUtils.getObject(inParam,"nums");
		List<Integer> questionids = new ArrayList<>();
		int i = 0;
		StringBuffer testid= new StringBuffer();
		Random random = new Random();
		for (int j = 0; j < Integer.parseInt(questionidNum); j++) {
			questionids.add(random.nextInt(10));
		}
		for (int m=0;m<6;m++)
		{
			testid.append(random.nextInt(10));
		}
		log.debug("试卷ID为："+questionids);
		for(Integer questionid : questionids){
			try{
				TestPage testPage = new TestPage();
				BeanUtils.populate(testPage, inParam);
				testPage.setQuestionid(questionid);
				testPage.setTestname(MapUtils.getString(inParam,"testname2"));
				testPage.setSubjectid(subjectService.getSubjectIdByname(MapUtils.getString(inParam,"subjectname2")));
				testPage.setTeacherid(Integer.parseInt(teacherService.getTeacherId((String)session.getAttribute("username"))));
				testPage.setTestid(Integer.parseInt(testid.toString()));
				int j= testPageService.insertTestPage(testPage);
				if(j == 1 ){
					i++;
				}
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		if(i == questionids.size()){
			return new Result().msg("新建试卷成功").success(true).data("成功");
		}else{
			return new Result().msg("新建试卷失败").success(false).data("失败");
		}
	}
	@Override
	public TableResult getQuestions(Map<String, Object> inParam) {
		HttpSession session = request.getSession();
		String subjectname = MapUtils.getString(inParam,"subjectname");
		log.debug("subjectname = "+ subjectname);
		String realname = (String)session.getAttribute("username");
		//获取教师添加试卷时的题库列表
		TableResult tableResult = this.getQuestionsByteacherName(realname);
		List<QuestionsDto> result = new ArrayList<>();
		List<QuestionsDto> questionsDto= HAUtils.castList(tableResult.getData(),QuestionsDto.class);
		for(QuestionsDto questionsDto1:questionsDto){
			if(subjectname .equals(questionsDto1.getSubjectname())){
				result.add(questionsDto1);
			}
		}
		int size = result.size();
		String count = size + "";
		return new TableResult().code(0).msg("获取数据成功").count(count).data(result);
	}

	@Override
	public TableResult queryExam() {
		List<Map<String,Object>> list = testPageService.queryExam();
		for (Map<String, Object> map : list) {
			map.put("teachername",teacherService.queryById(MapUtils.getString(map,"teacherid")).getRealname());
			map.put("subjectname",MapUtils.getString(subjectService.getSubjectNameById(MapUtils.getString(map,"subjectid")),"subjectname"));
		}
		int size = list.size();
		String count = size + "";
		return new TableResult().code(0).msg("获取数据成功").count(count).data(list);
	}

	@Override
	public List<Map<String, Object>> getAllInfo() {
		return teacherService.getAllInfo();
	}

	@Override
	public List<Map<String, Object>> readPage() {
		return stuSubService.getReadPage();
	}

	@Override
	public int modifyscore(Map<String, Object> map) {
		return stuExamService.updateScore(map);
	}

	@Override
	public TableResult queryScore1(String username) {
		List<Map<String, Object>> list = stuExamService.queryScore1(username);
		list.forEach(map->{
			String testname = MapUtils.getString(map, "testname");
			Map<String,Object> map2 = stuExamService.getTotalScore(testname);
			Integer totalscore = MapUtils.getInteger(map2, "totalscore");
			Integer count = MapUtils.getInteger(map2, "count");
			int average = totalscore/count;
			map.put("average",average);
			map.put("passrate","100%");
		});
		TableResult tr = new TableResult();
		log.debug(list+"");
		tr.data(list);
		tr.code(0);
		tr.count(list.size()+"");
		return tr;
	}


}
